package com.xique.auth.service;

import com.xique.auth.form.AppLoginBody;
import com.xique.common.core.constant.CacheConstants;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.domain.R;
import com.xique.common.core.enums.UserStatus;
import com.xique.common.core.exception.BaseException;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.ServletUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.sign.RsaUtils;
import com.xique.door.api.RemoteAppLoginLogService;
import com.xique.door.api.RemoteAppUserService;
import com.xique.door.api.RemoteWxLoginService;
import com.xique.door.api.dto.BaseUserDTO;
import com.xique.door.api.model.LoginAppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author shd
 * @create 2021/12/31 10:15
 */
@Component
public class AppLoginService {

    @Autowired
    private RemoteAppUserService remoteAppUserService;

    @Autowired
    private RemoteAppLoginLogService remoteAppLoginLogService;

    @Autowired
    private RemoteWxLoginService remoteWxLoginService;

    @Value("${xique.api.privateKey}")
    private String privateKey;

    /** ================================================================C端登录====================================================== **/

    public LoginAppUser login(String loginName, String password) {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        try {
            password = RsaUtils.decryptByPrivateKey(privateKey, password);
        } catch (Exception e) {
            throw new BaseException("密码解析错误");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(loginName, password))
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "用户/密码必须填写", platform);
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "用户密码不在指定范围", platform);
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "用户名不在指定范围", platform);
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginAppUser> userResult = remoteAppUserService.getUserInfo(loginName);
        if (R.FAIL == userResult.getCode())
        {
            throw new BaseException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "登录用户不存在", platform);
            throw new BaseException("登录用户：" + loginName + " 不存在");
        }
        LoginAppUser userInfo = userResult.getData();
        BaseUserDTO user = userResult.getData().getUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", platform);

            throw new BaseException("对不起，您的账号：" + loginName + " 已被删除");
        }
        if (UserStatus.USER_DISABLE.getCode().equals(user.getStatus()))
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", platform);
            throw new BaseException("对不起，您的账号：" + loginName + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_FAIL, "用户密码错误", platform);
            throw new BaseException("用户不存在/密码错误");
        }
        remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGIN_SUCCESS, "登录成功", platform);
        return userInfo;
    }

    public void logout(String loginName)
    {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        remoteAppLoginLogService.saveLoginLog(loginName, Constants.LOGOUT, "退出成功", platform);
    }

    /** ================================================================C端微信登录====================================================== **/

    public String getPhone(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new BaseException("code不能为空");
        }
        R<String> result = remoteWxLoginService.getPhone(code);
        if (R.FAIL == result.getCode()) {
            throw new BaseException(result.getMsg());
        }
        return result.getData();
    }

    public String sendAuthCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new BaseException("phone不能为空");
        }
        R<String> result = remoteWxLoginService.sendAuthCode(phone);
        if (R.FAIL == result.getCode()) {
            throw new BaseException(result.getMsg());
        }
        return result.getData();
    }

    public LoginAppUser wxLogin(AppLoginBody body) {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        if (StringUtils.isEmpty(body.getPhone())) {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "手机号不能为空", platform);
            throw new BaseException("手机号不能为空");
        }
        if (StringUtils.isEmpty(body.getWxCode())) {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "code不能为空", platform);
            throw new BaseException("code不能为空");
        }
        R<LoginAppUser> userResult = remoteWxLoginService.login(body.getPhone(), body.getWxCode());
        if (R.FAIL == userResult.getCode()) {
            throw new BaseException(userResult.getMsg());
        }
        LoginAppUser userInfo = userResult.getData();
        BaseUserDTO user = userResult.getData().getUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除", platform);

            throw new BaseException("对不起，您的账号：" + body.getPhone() + " 已被删除");
        }
        if (UserStatus.USER_DISABLE.getCode().equals(user.getStatus()))
        {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员", platform);
            throw new BaseException("对不起，您的账号：" + body.getPhone() + " 已停用");
        }
        remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_SUCCESS, "登录成功", platform);
        return userInfo;
    }

    public LoginAppUser verificationCode(AppLoginBody body) {
        String platform = ServletUtils.getHeaders(Objects.requireNonNull(ServletUtils.getRequest())).get(CacheConstants.DETAILS_PLATFORM_TYPE);
        if (StringUtils.isEmpty(body.getPhone())) {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "手机号不能为空", platform);
            throw new BaseException("手机号不能为空");
        }
        if (StringUtils.isEmpty(body.getCode())) {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "验证码不能为空", platform);
            throw new BaseException("验证码不能为空");
        }
        R<LoginAppUser> userResult = remoteWxLoginService.verificationCode(body.getPhone(), body.getCode());
        if (R.FAIL == userResult.getCode()) {
            throw new BaseException(userResult.getMsg());
        }
        LoginAppUser userInfo = userResult.getData();
        BaseUserDTO user = userResult.getData().getUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除", platform);

            throw new BaseException("对不起，您的账号：" + body.getPhone() + " 已被删除");
        }
        if (UserStatus.USER_DISABLE.getCode().equals(user.getStatus()))
        {
            remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员", platform);
            throw new BaseException("对不起，您的账号：" + body.getPhone() + " 已停用");
        }
        remoteAppLoginLogService.saveLoginLog(body.getPhone(), Constants.LOGIN_SUCCESS, "登录成功", platform);
        return userInfo;
    }

}


